package io.dcloud.uniplugin;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;


public class AdMobModule extends UniModule {

    String TAG = "testAdMob";
    public static int REQUEST_CODE = 1000;
    private UniJSCallback uniJSCallback;


    //run ui thread
    @UniJSMethod(uiThread = false)
    public void loadVideoAd(JSONObject options, UniJSCallback callback) {
        String codeId = options.getString("codeId");
        Log.e(TAG, "loadVideoAd--" + codeId);
        if (callback != null) {
            uniJSCallback = callback;
            if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
                Intent intent = new Intent(mUniSDKInstance.getContext(), NativePageActivity.class);
                intent.putExtra("codeId", codeId);
                ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
            }
        }
    }

    //run JS thread
    @UniJSMethod(uiThread = false)
    public JSONObject testSyncFunc() {
        JSONObject data = new JSONObject();
        data.put("code", "success");
        return data;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && data.hasExtra("isRewardValid")) {
            Log.e(TAG, "原生页面返回----" + data.getBooleanExtra("isRewardValid",false));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("action", data.getStringExtra("action"));
            jsonObject.put("isRewardValid", data.getBooleanExtra("isRewardValid", false));
            jsonObject.put("code", data.getIntExtra("code", -1));
            uniJSCallback.invoke(jsonObject);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

}
